import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from 'view/user/login';
import Homelayout from '../layout/Homelayout'
import NotFound from "view/404"
import Welcome from "view/welcome"
import store from 'store'
import userList from '../views/userList.vue'
import roles from '../views/right/roles.vue'
import rights from '../views/right/rights.vue'
import params from "../views/goods/params.vue"
import Categories from 'view/categories/categories'

Vue.use(VueRouter)

const routes = [{
        path: "/login",
        name: "login",
        component: Login
    },
    {
        redirect: "/welcome",
        path: "/",
        name: "homelayout",
        component: Homelayout,
        children: [

            {
                path: "/welcome",
                name: "welcome",
                component: Welcome
            },
            {
                path: "/users",
                name: "users",
                component: userList
            },
            {
                path: "/roles",
                name: "roles",
                component: roles
            },
            {
                path: "/rights",
                name: "rights",
                component: rights
            },
            {
                path: "/goods",
                name: "goods",
                component: () =>
                    import ("../views/goods/goods.vue")
            },
            {
                path: "/params",
                name: "params",
                component: params

            },
            {
                path: "/categories",
                name: "categories",
                component: Categories

            },
            {
                path: "/orders",
                name: "orders",
                component: () =>
                    import ("../views/orders/orders.vue")

            },
            {
                path: "*",
                name: "404",
                component: NotFound
            },
        ]
    },

]

const router = new VueRouter({
    mode: 'history',
    base: process.env.BASE_URL,
    routes
});



router.beforeEach((to, from, next) => {
    const token = store.getters.token;
    const isLogin = to.name === 'login';
    // 如果有token 并且在登录页 那么就跳转页面
    if (token && isLogin) {
        return next({ name: "homelayout" });
    }
    // 如果没有token 并且不是在登录页 那么久跳转到登录页
    if (!token && !isLogin) {
        return next({ name: "login" })
    }
    // 其他正常
    next();
})

export default router